﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;
using EvaluationSystem.DAO;
using System.Text;
using EvaluationSystem.Exceptions;

namespace EvaluationSystem.ConfigurationPages
{
    public partial class StaffAdding : System.Web.UI.Page
    {
        StaffManager staffManager = new StaffManager();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Utility.IsLogin(this.Page))
            {
#if !DEBUG
                Response.Redirect("../Default.aspx");
#endif
            }
            if (!X.IsAjaxRequest)
            {
                InitRoles();
                InitGroups();
            }
        }

        private void InitGroups()
        {
            DataTable dt = staffManager.GetGroups();
            Ext.Net.TreeNode root = new Ext.Net.TreeNode();
            foreach (DataRow row in dt.Rows)
            {
                Ext.Net.TreeNode node = new Ext.Net.TreeNode(row[0].ToString(), row[1] as string, Icon.ArrowJoin);
                node.Checked = ThreeStateBool.False;
                node.Leaf = true;
                root.Nodes.Add(node);
            }
            tpGroup.Root.Add(root);
        }

        private void InitRoles()
        {
            StringBuilder sbToolTip = new StringBuilder();
            DataTable dt = staffManager.GetRoles();
            foreach (DataRow row in dt.Rows)
            {
                Ext.Net.ListItem item = new Ext.Net.ListItem(row[1] as string);
                item.Value = row[0].ToString();
                cbbRole.Items.Add(item);
                sbToolTip.Append(String.Format("<table><tr><td width=70>{0}</td><td width=200>{1}</td></tr></table>", row[1] as string, row[2] as string));
                if (row[1].Equals("组员"))
                {
                    cbbRole.SelectedIndex = cbbRole.Items.Count - 1;
                }
            }

            tooltipForRole.Html = sbToolTip.ToString();
        }

        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            try
            {
                bool isSuccess = staffManager.AddStaff(txtUsername.Text.Trim(),Utility.MD5(txtPassword.Text.Trim()), ddfGroup.Text, cbbRole.Value.ToString());
                if (isSuccess)
                {
                    X.MessageBox.Notify(Constants.Noticfy, "增加用户成功.").Show();
                }
                else
                {
                    X.MessageBox.Alert(Constants.Noticfy, "保存出错，请重新尝试或联系开发人员.").Show();
                }
            }
            catch (InvalidUserException ex)
            {
                X.MessageBox.Alert(Constants.Noticfy, ex.Message).Show();
                txtUsername.Focus();
                txtUsername.SelectText(0);
            }
        }
    }
}